<?php
namespace frontend\widgets\post;

/**
 * 文章列表组件
 */

use common\models\PostsModel;
use common\models\RelationPostTagsModel;
use common\models\TagsModel;
use frontend\models\PostsForm;
//use http\Url;
use yii\helpers\Url;
use yii\base\Widget;
use yii\data\Pagination;
use yii\db\Query;
class PostWidget extends Widget{
    //文章列表标题
    public $title = '';
    //每页显示条数
    public $limit = 6;
    // 是否显示更多
    public $more = true;
    // 是否显示分页
    public $page = true;
    // 某一用户下的博客
    public $user_id = 0;
    // 日期搜索
    public $search_date = '';
    public function run()
    {
        $curPage = \Yii::$app->request->get('page',1);
        $tag = \Yii::$app->request->get('tag');
        //查询条件
        if(!empty($tag)){
            $ids = [];

            //方法一：使用with关联表
            //$tags = new TagForm();
            //$ids = $tags->getIdsByTag(['tag_name'=>$tag]);

            //方法二：先查询标签id，再查询文章id数组
            //$data = TagsModel::find()->where(['tag_name'=>$tag])->asArray()->one();
            //$ids = RelationPostTagsModel::getPostIds($data['id']);

            //方法三：使用join关联表
            $data = (new Query())
                ->select('a.post_id')
                ->from(['a'=>RelationPostTagsModel::tableName()])
                ->join('LEFT JOIN',['b'=>TagsModel::tableName()],'a.tag_id=b.id')
                ->where(['b.tag_name'=>$tag])
                ->orderBy(['a.post_id'=>SORT_DESC])
                ->all();

            if(!empty($data)){
                foreach ($data as $value){
                    $ids[] = $value['post_id'];
                }
            }
            $cond = ['id'=>$ids,'is_valid'=>PostsModel::IS_VALID];
        }else{
            $cond = ['is_valid'=>PostsModel::IS_VALID];
        }

        //$user_id
        $this->user_id && $cond['user_id'] = $this->user_id;
        //日期搜索
        if($this->search_date){
            $search_date_start = strtotime(date('Y-m-d 00:00:01', strtotime($this->search_date)));
            $search_date_end = strtotime(date('Y-m-d 23:59:59', strtotime($this->search_date)));
            $cond = ['and',['>','created_at',$search_date_start],['<','created_at',$search_date_end],$cond];
        }
//        var_dump($cond);
//        die;
//        //查询条件
//        $cond = ['=','is_valid',PostsModel::IS_VALID];
//        $tag && $cond = ['and',['=','is_valid',PostsModel::IS_VALID],['=','tags.tag_name',$tag]];
        $res = PostsForm::getList($cond, $curPage, $this->limit);
        $result['title'] = $this->title ?: '最新文章';
        $result['more'] = Url::to(['posts/index']);
        $result['body'] = $res['data'] ?: [];
        //是否显示分页
        if($this->page){
            $pages = new Pagination(['totalCount'=>$res['count'],'pageSize'=>$res['pageSize']]);
            $result['page'] = $pages;
        }
        return $this->render('index',['data'=>$result]);
    }

}